﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class bbs_bbs_new : System.Web.UI.Page
{
    protected string menu2_id, topic, title_id, menu2_name;
    protected int emplid_int = 0;
    protected string emplusername_str = "";
    protected int i = 0;

    protected string[] myArray = new string[20];		//上传图片文件名称
    protected string[] myArrayRemark = new string[20];	//上传图片文件说明
    protected string[] myArrayw = new string[20];		//上传图片文件width
    protected string[] myArrayh = new string[20];		//上传图片文件height
    protected string[] myFile = new string[3];		//上传附件文件名称
    protected string[] myFileRemark = new string[3];
    //上传附件文件说明
    protected string[] myTrueFile = new string[3];

    protected void Page_Load(object sender, EventArgs e)
    {
        //emplid_int = Int32.Parse(Session["uid"].ToString());
        //MembershipUser singleUser = Membership.GetUser();
        //emplusername_str = singleUser.UserName;

        menu2_id = "10001";// Request.Params["menu2_id"];
        menu2_name = Request.Params["menu2_name"];
        topic = menu2_id + "/";			//新帖子先属于当前栏目
        if (!Page.IsPostBack)
        {
            fjwindows.Visible = false;
            docwindows.Visible = false;

            nr1.OnlyRead = false;
            nr1.ToolbarDisplay = true;
            nr1.text = "";
            nr1.CodeMode = false;
            //获得了二级栏目编号，可以去查找其子栏目名称
            setSubbbs();
            //是否显示属性设置
            //this.DisplayImp();
        }
    }

    protected void setSubbbs()
    {
        //栏目有子栏目，表subbbs2
        
        Conn conn = new Conn();
        //判断有没有子栏目
        string sql = "select subbbs_id from subbbs where bbs_id=" + menu2_id;
        string subbbs_id = conn.sqlFirst(sql);
        ddlsubbs.Visible = true;
        lasubbs.Visible = true;

        if (subbbs_id != "0")
        {
            //子栏目列表
            ddlsubbs.Items.Add("未选");
            string Sql2 = "select subbbs_id,subbbs_name from subbbs where bbs_id=" + menu2_id;
            SqlDataReader ForumUsers2 = conn.GetList(Sql2);
            while (ForumUsers2.Read())
            {
                ListItem iList = new ListItem(ForumUsers2.GetString(1), ForumUsers2.GetInt32(0).ToString());
                ddlsubbs.Items.Add(iList);
            }
            ForumUsers2.Close();
        }
        else
        {
            ddlsubbs.Items.Add("未选");
        }
        conn.Dispose();
    }


    //private void DisplayImp()
    //{
    //    //判断dutyno是否可以添加新闻、的重要性
    //    string sfname = Session["sfname"].ToString();
    //    if ((sfname == "系统管理员") | (sfname == "园长") | (sfname == "园长助理"))
    //    {
    //        Label1.Visible = true;
    //        TBimp.Visible = true;
    //        CBsoul.Visible = true;
    //        isnews.Visible = true;
    //    }
    //}

    protected void displayfj(Object sender, EventArgs e)
    {///允许上载图片
        addwindows.Visible = false;
        fjwindows.Visible = true;
        docwindows.Visible = false;
    }

    protected void displaydoc(Object sender, EventArgs e)
    {///允许上载文件
        addwindows.Visible = false;
        fjwindows.Visible = false;
        docwindows.Visible = true;
    }

    protected void upload_doc(Object sender, EventArgs e)
    {///完成，实际上就是把文件上传。
        int errorno = 0;

        if ((File1.PostedFile == null) & (File2.PostedFile == null) & (File3.PostedFile == null))
        {
            me.Text = "请先选择一个上传文件";
            errorno = 1;
        }
        else
        {
            if ((File1.PostedFile.FileName.Length < 3) & (File2.PostedFile.FileName.Length < 3) & (File3.PostedFile.FileName.Length < 3))
            {
                me.Text = "请先选择一个上传文件";
                errorno = 1;
            }
            else
            {
                if (File1.PostedFile.FileName.Length >= 3)
                {
                    if (File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.Length - 3).ToLower() == "exe")
                    {
                        me.Text = "请不要上传EXE文件";
                        errorno = 1;
                    }
                }
                if (File2.PostedFile.FileName.Length >= 3)
                {
                    if (File2.PostedFile.FileName.Substring(File2.PostedFile.FileName.Length - 3).ToLower() == "exe")
                    {
                        me.Text = "请不要上传EXE文件";
                        errorno = 1;
                    }
                }
                if (File3.PostedFile.FileName.Length >= 3)
                {
                    if (File3.PostedFile.FileName.Substring(File3.PostedFile.FileName.Length - 3).ToLower() == "exe")
                    {
                        me.Text = "请不要上传EXE文件";
                        errorno = 1;
                    }
                }

                if ((File1.PostedFile.ContentLength == 0) & (File2.PostedFile.ContentLength == 0) & (File3.PostedFile.ContentLength == 0))
                {
                    me.Text = "请先选择一个上传文件";
                    errorno = 1;
                }
                if ((File1.PostedFile.ContentLength > 400000) | (File2.PostedFile.ContentLength > 400000) | (File3.PostedFile.ContentLength > 400000))
                {
                    me.Text = "文件大小限定在400K以内";
                    if (File1.PostedFile.ContentLength > 400000)
                    {
                        me.Text = me.Text + ",第一个文件" + File1.PostedFile.ContentLength / 1000 + "K";
                        errorno = 1;
                    }
                    if (File2.PostedFile.ContentLength > 400000)
                    {
                        me.Text = me.Text + ",第二个文件" + File2.PostedFile.ContentLength / 1000 + "K";
                        errorno = 1;
                    }
                    if (File3.PostedFile.ContentLength > 400000)
                    {
                        me.Text = me.Text + ",第三个文件" + File3.PostedFile.ContentLength / 1000 + "K。";
                        errorno = 1;
                    }
                }
            }
        }
        if (errorno == 0)
        {
            me.Text = "";
            if (File1.PostedFile.ContentLength > 0)
                this.SaveDoc(File1.PostedFile.FileName, tbf1.Text, 0, File1);
            if (File2.PostedFile.ContentLength > 0)
                this.SaveDoc(File2.PostedFile.FileName, tbf2.Text, 1, File2);
            if (File3.PostedFile.ContentLength > 0)
                this.SaveDoc(File3.PostedFile.FileName, tbf3.Text, 2, File3);
            //返回到标题、内容的输入页面
            addwindows.Visible = true;
            fjwindows.Visible = false;
            docwindows.Visible = false;
        }
    }

    protected void SaveDoc(string s, string remark, int k, HtmlInputFile up_file)
    {//提供浏览文件路径保存到服务器
        string first_filename;
        int pos;
        s = s.Trim();
        s = s.Replace("'", "’");
        remark = remark.Trim();
        remark = remark.Replace("'", "’");
        pos = s.LastIndexOf("\\");
        first_filename = s.Substring(pos + 1);
        first_filename = first_filename.Replace(" ", "");

        //获得绝对路径
        string path = Server.MapPath("uploadimage");
        //建立新的文件名的格式：时间＋用户名＋文件后缀(由于中文名称会出现错误，去掉原文件名）
        string filename = DateTime.Now.ToString("yyyy'-'MM'-'d hh':'mm':'ss");
        filename = filename.Replace(":", "");
        filename = filename.Replace("-", "");
        filename = filename.Replace(" ", "");
        filename = filename + Session["uname"];
        string filename_suffix = first_filename.Substring(first_filename.IndexOf("."));
        string filename_prefix = first_filename.Substring(0, first_filename.IndexOf(".") - 1);
        filename = filename + "doc" + k.ToString() + filename_suffix;
        //			filename=filename+first_filename;

        //将文件名保存至数组
        myFile[k] = filename;
        ViewState.Add("myFile[" + k.ToString() + "]", myFile[k]);

        myFileRemark[k] = remark;
        ViewState.Add("myFileRemark[" + k.ToString() + "]", myFileRemark[k]);

        myTrueFile[k] = first_filename;
        ViewState.Add("myTrueFile[" + k.ToString() + "]", myTrueFile[k]);

        //保存文件至物理路径
        filename = path + "/" + filename;
        up_file.PostedFile.SaveAs(filename);
    }

    protected void upload(Object sender, EventArgs e)
    {///粘贴，实际上就是把文件上传。并且保存文件说明
        int errorno = 0;

        if (upload_file.PostedFile == null)
        {
            wc.InnerHtml = "请先选择一个图片再点粘贴";
            errorno = 1;
        }
        else
        {
            if (upload_file.PostedFile.FileName.Length < 3)
            {
                wc.InnerHtml = "请先选择一个图片再点粘贴";
                errorno = 1;
            }
            else
            {
                if (upload_file.PostedFile.FileName.Substring(upload_file.PostedFile.FileName.Length - 3).ToLower() != "gif" && upload_file.PostedFile.FileName.Substring(upload_file.PostedFile.FileName.Length - 3).ToLower() != "jpg" && upload_file.PostedFile.FileName.Substring(upload_file.PostedFile.FileName.Length - 3).ToLower() != "bmp")
                {
                    wc.InnerHtml = "图片格式只接受 jpg,gif,bmp三种格式,您上传的图片格式不对";
                    errorno = 1;
                }
                if (upload_file.PostedFile.ContentLength == 0)
                {
                    wc.InnerHtml = "请先选择一个图片再点粘贴";
                    errorno = 1;
                }
                if (upload_file.PostedFile.ContentLength > 150000000)
                {
                    wc.InnerHtml = "<font size=2 color=#ff0066>图片大小限定在1.5M以内</font>";
                    errorno = 1;
                }
            }
        }
        if (errorno == 0)
        {
            //				//true_file="*"+upload_file.PostedFile.FileName;	//保存多个原来的文件名,以*号开头
            //				//获得原来的文件名
            string first_filename;
            int pos;
            pos = upload_file.PostedFile.FileName.LastIndexOf("\\");
            first_filename = upload_file.PostedFile.FileName.Substring(pos + 1);
            first_filename = first_filename.Replace(" ", "");

            //获得绝对路径
            string path = Server.MapPath("uploadimage");
            //建立新的文件名的格式：时间＋用户名(由于中文名称会出现错误，去掉原文件名）
            string filename = DateTime.Now.ToString("yyyy'-'MM'-'d hh':'mm':'ss");
            filename = filename.Replace(":", "");
            filename = filename.Replace("-", "");
            filename = filename.Replace(" ", "");
            filename = filename + Session["uname"];
            string filename_suffix = first_filename.Substring(first_filename.IndexOf("."));

            if (ViewState["i"] == null)
                i = 0;
            else
                i = (int)ViewState["i"];

            filename = filename + "img" + i.ToString() + filename_suffix;
            //将文件名保存至数组
            myArray[i] = filename;
            ViewState.Add("myArray[" + i.ToString() + "]", myArray[i]);
            myArrayRemark[i] = picRemark.Text.Trim();
            ViewState.Add("myArrayRemark[" + i.ToString() + "]", myArrayRemark[i]);

            //保存文件至物理路径
            string filename2 = path + "/" + filename;
            upload_file.PostedFile.SaveAs(filename2);

            //保存文件width,height
            System.Drawing.Image image = System.Drawing.Image.FromFile(filename2);
            int h = image.Height;
            int w = image.Width;
            myArrayw[i] = w.ToString();
            ViewState.Add("myArrayw[" + i.ToString() + "]", myArrayw[i]);
            myArrayh[i] = h.ToString();
            ViewState.Add("myArrayh[" + i.ToString() + "]", myArrayh[i]);
            image.Dispose();

            //添加到列表框中并显示出来
            removefile.Items.Add(new ListItem(filename, "" + upload_file.PostedFile.ContentLength));
            int m = removefile.Items.IndexOf(new ListItem(filename, "" + upload_file.PostedFile.ContentLength));
            removefile.SelectedIndex = m;
            if ((myArrayw[i] != "") & (myArrayw[i] != null))
            {
                if (Int32.Parse(myArrayw[i]) > 600)
                    displayupload.InnerHtml = "<img width=600 src=\"uploadimage/" + filename + "\">";
                else
                    displayupload.InnerHtml = "<img src=\"uploadimage/" + filename + "\">";
            }
            else
                displayupload.InnerHtml = "<img src=\"uploadimage/" + filename + "\">";


            wc.Visible = false;
            int intfilesize;
            int totlesize;
            totlesize = Int32.Parse(totlephotosize.Value) + upload_file.PostedFile.ContentLength;
            totlephotosize.Value = "" + totlesize;
            float filesize = (float)totlesize / 1024;
            intfilesize = (int)(filesize * 10);
            filesize = (float)intfilesize / 10;
            photosize.InnerHtml = "" + filesize + "k";

            if (ViewState["i"] == null)
            {
                i = i + 1;
                ViewState.Add("i", i);
            }
            else
            {
                ViewState.Add("i", (int)ViewState["i"] + 1);
            }
            //				myArray[i]=filename;
            //				ViewState.Add("myArray["+i.ToString()+"]",myArray[i]);
        }
        else
        {
            wc.Visible = true;
        }
    }


    protected void displayadd(Object sender, EventArgs e)
    {
        addwindows.Visible = true;
        fjwindows.Visible = false;
    }

    protected void selectpic(Object sender, EventArgs e)
    {//选择附件
        if (removefile.SelectedItem.Value != "nodelete")
        {
            displayupload.InnerHtml = "<img src=\"uploadimage/" + removefile.SelectedItem.Text + "\">";
        }
    }


    protected void remove(Object sender, EventArgs e)
    {///删除附件
        int totlesize = 0;
        if (removefile.SelectedItem.Value != "nodelete")
        {
            if (removefile.Items.Count == 2)
            {
                photosize.InnerHtml = "0.0k";
                totlephotosize.Value = "0";
            }
            else
            {
                totlesize = Int32.Parse(totlephotosize.Value) - Int32.Parse(removefile.SelectedItem.Value);
                totlephotosize.Value = "" + totlesize;
                float filesize = (float)totlesize / 1024;
                int intfilesize = (int)(filesize * 10);
                filesize = (float)intfilesize / 10;
                photosize.InnerHtml = "" + filesize + "k";
            }

            string removefilename = removefile.SelectedItem.Text;
            //imgfile=imgfile.Replace("*"+removefilename,"");//删除文件名

            for (int n = 0; n < myArray.Length; n++)
            {
                if (myArray[n] == removefilename)
                    myArray[n] = "";
            }

            string removefilesize = removefile.SelectedItem.Value;
            removefile.Items.Remove(new ListItem(removefilename, removefilesize));
            removefilename = Server.MapPath("uploadimage") + "/" + removefilename;
            File.Delete(removefilename);
            displayupload.InnerHtml = "";
        }
    }


    protected void add(object sender, System.EventArgs e)
    {//发表        
        Session["CPxiangce"] = 0;
        string zhuti, nr, isname, uname1, username, writer, isnews, CBsoul;
        zhuti = Request.Params["zhuti"];		//标题
        //================格式转换======================
        zhuti = zhuti.Replace("'", "''");
        nr = nr1.text;
        nr = nr.Replace("'", "''");
        //==============================================

        isname = Request.Params["isname"];	//匿名
        isnews = Request.Params["isnews"];	//新闻快讯
        CBsoul = Request.Params["CBsoul"];	//匿名

        string imp = TBimp.Text.Trim();	//新闻重要性
        if (imp == "")
            imp = "0";

        //username = (string)Session["uname"];		//用户名
        MembershipUser singleUser = Membership.GetUser();
        username = singleUser.UserName;
        string ip = Request.UserHostAddress;		//IP
        string posttime = DateTime.Now.ToString();	//时间

        Conn conn = new Conn();

        //writer = Session["uname1"].ToString();
        writer = singleUser.UserName;

        uname1 = singleUser.UserName;
        //string sfid = Session["sfid"].ToString();
        //string sfname = Session["sfname"].ToString();
        //string yid = Session["yid"].ToString();
        //string yname = Session["yname"].ToString();
        //string uid = Session["uid"].ToString();


        if (isnews == "on")
            topic += conn.s_news + "/";

        if (CBsoul == "on")
            topic += conn.s_elite + "/";

        //选择子栏目，确定subbbs_id
        string subbbs_id = "0";
        if (ddlsubbs.Visible)
        {
            if (ddlsubbs.SelectedItem.Text != "未选")
            {
                string subbbs_name = ddlsubbs.SelectedItem.Text;
                string sub_sql = "select subbbs_id from subbbs2 where menu2_id = " + menu2_id + " and subbbs_name='" + subbbs_name + "'";
                subbbs_id = conn.sqlFirst(sub_sql);
            }
        }

        string InsertSql = "insert into bbs(f_title,f_content,f_writer,f_username1,f_ip,f_topic,f_imp,f_subbbs) " +
            "values('" + zhuti + "','" + nr + "'," + username + ",'" + username + "'," + ip + ",'" + topic + "'," + imp + "," + subbbs_id + ")";
        conn.Conn_Insert(InsertSql);
        //			imgfile=null;

        //找到title_id
        string SSql = "select title_id from bbs where f_ip='" + ip + "' and f_date='" + posttime + "' and f_title='" + zhuti + "'";
        string maxid = conn.sqlFirst(SSql);

        //添加图片文件
        if (ViewState["i"] != null)
        {
            for (int k = 0; k < (int)ViewState["i"]; k++)
            {
                if ((string)ViewState["myArray[" + k + "]"] != "")
                {
                    string InsertImgSql = "insert into ImgUpload(title_id,f_filename,flag,f_remark,f_width,f_height) values(" + maxid + ",'" + (string)ViewState["myArray[" + k + "]"] + "',1,'" + (string)ViewState["myArrayRemark[" + k + "]"] + "','" + (string)ViewState["myArrayw[" + k + "]"] + "','" + (string)ViewState["myArrayh[" + k + "]"] + "')";
                    conn.Conn_Insert(InsertImgSql);
                }
            }
        }

        //添加附件文件
        for (int mm = 0; mm < 3; mm++)
        {
            if (((string)ViewState["myFile[" + mm + "]"] != "") & ((string)ViewState["myFile[" + mm + "]"] != null))
            {
                string InsertFileSql = "insert into ImgUpload(title_id,f_filename,f_remark,f_truename,flag) values(" + maxid + ",'" + (string)ViewState["myFile[" + mm + "]"] + "','" + (string)ViewState["myFileRemark[" + mm + "]"] + "','" + (string)ViewState["myTrueFile[" + mm + "]"] + "',2)";
                conn.Conn_Insert(InsertFileSql);
            }
        }

        //静态变量复位
        i = 0;
        for (int n = 0; n < 20; n++)
            myArray[n] = null;
        for (int nn = 0; nn < 3; nn++)
            myFile[nn] = null;

        conn.Dispose();
        string s = "bbs_List.aspx?menu2_id=" + menu2_id + "&menu2_name=" + menu2_name;
        Response.Redirect(s);
        Response.End();
    }

    protected void Button8_Click(object sender, System.EventArgs e)
    {
        addwindows.Visible = true;
        fjwindows.Visible = false;
        docwindows.Visible = false;
    }
}
